package com.serkol.ams.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.entity.Printers;
import com.serkol.ams.entity.Users;
import com.serkol.ams.entity.UsersAuthentication;
import com.serkol.ams.mapper.PrintersMapper;
import com.serkol.ams.service.*;
import com.serkol.handler.MyLambdaQueryWrapper;
import com.serkol.wx.bean.OrderSuccessMsg;
import com.serkol.wx.bean.TiChengMsg;
import com.serkol.wx.service.WechatMpMessageService;
import me.chanjar.weixin.common.error.WxErrorException;
import net.xpyun.platform.opensdk.service.PrintService;
import net.xpyun.platform.opensdk.service.PrintServiceImpl;
import net.xpyun.platform.opensdk.util.Config;
import net.xpyun.platform.opensdk.util.PrinterQuery;
import net.xpyun.platform.opensdk.vo.ObjectRestResponse;
import net.xpyun.platform.opensdk.vo.PrintRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* @author pingan
* @description 针对表【printers】的数据库操作Service实现
* @createDate 2023-12-25 19:24:54
*/
@Service
public class PrintersServiceImpl extends ServiceImpl<PrintersMapper, Printers>
    implements PrintersService{
    @Autowired
    private OrderMasterService masterService;
    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private UsersService usersService;
    @Autowired
    private UsersAuthenticationService usersAuthenticationService;
    @Autowired
    private WechatMpMessageService wechatMpMessageService;
    @Autowired
    private UsersWalletLogService usersWalletLogService;

    @Override
    public List<String> serialIds() {
        MyLambdaQueryWrapper<Printers> queryWrapper=new MyLambdaQueryWrapper<>();
        queryWrapper.select(Printers::getSerialId).as("serialId");

        return this.listObjs(queryWrapper, o -> {
           return String.valueOf(o);
       });
    }

    @Override
    public boolean updatePrinter(List<String> successList, List<String> errorList) {
        boolean flag=false;

        if(successList.size()>0) {
            LambdaUpdateWrapper<Printers> updateWrapperSuc=new LambdaUpdateWrapper<>();
            updateWrapperSuc.in(Printers::getSerialId,successList).set(Printers::getStatus,1);
            flag = this.update(updateWrapperSuc);
        }
        if(errorList.size()>0) {
            LambdaUpdateWrapper<Printers> updateWrapperSuc=new LambdaUpdateWrapper<>();
            updateWrapperSuc.in(Printers::getSerialId,errorList).set(Printers::getStatus,0);
            flag = this.update(updateWrapperSuc);
        }


        return flag;
    }

    @Override
    public boolean sendPrinter(Long orderId) {
         Map<String, Object> mapById = masterService.findMapById(orderId);
         //findByOrderDetailList
         List<Map<String, Object>> byOrderDetailList = detailService.findByOrderDetailList(orderId);
         String printContent = getPrenter(mapById, byOrderDetailList);
         List<Printers> list = this.list();
         Iterator<Printers> iterator = list.iterator();
        while (iterator.hasNext()) {
             Printers next = iterator.next();
             sendData(printContent,next);
        }
        long userId = (long) mapById.get("userId");
        Users byUserId = usersService.findByUserId(userId);
        BigDecimal paymentAmount = (BigDecimal) mapById.get("paymentAmount");
        OrderSuccessMsg orderSuccessMsg=new OrderSuccessMsg();
        orderSuccessMsg.setAmount5(paymentAmount.doubleValue());
        String format = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        orderSuccessMsg.setTime6(format);
        if(byUserId!=null){
            List<Users> users = usersService.findByAdminList();
            UsersAuthentication findByUserId = usersAuthenticationService.getFindByUserId(byUserId.getId());
            if(findByUserId!=null){
              orderSuccessMsg.setThing13(findByUserId.getName());
            }
            Long parentUserId = byUserId.getParentUserId();
           if(parentUserId!=null){
               UsersAuthentication findByUserId1 = usersAuthenticationService.getFindByUserId(byUserId.getParentUserId());
               if(findByUserId1!=null){
                   orderSuccessMsg.setThing11(findByUserId1.getName());
               }
           }
            try {
                for (Users user : users) {
                    if(user.getMpOpenid()!=null){
                        orderSuccessMsg.setOpenId(user.getMpOpenid());
                        wechatMpMessageService.sendMessage(orderSuccessMsg);
                    }

                }
                List<TiChengMsg> wxMsg = usersWalletLogService.getWxMsgs(orderId);
                for (TiChengMsg tiChengMsg : wxMsg) {

                        tiChengMsg.setAmount2(paymentAmount);
                        if(tiChengMsg.getOpenId()!=null){
                            wechatMpMessageService.sendTiChengMessage(tiChengMsg);
                        }

                     //   wechatMpMessageService.sendTiChengMessage(tiChengMsg);

                }

             //   wechatMpMessageService.sendMessage(orderSuccessMsg);
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }
        }


        return true;
    }
    private  boolean  sendData(String printContent,Printers printers){
        PrintService printService=new PrintServiceImpl();
        PrintRequest request = new PrintRequest();
        Config.createRequestHeader(request);
        //*必填*：打印机编号
        request.setSn(printers.getSerialId());
        //*必填*：打印内容,不能超过12K
        request.setContent(printContent.toString());
        //打印份数，默认为1
        request.setCopies(1);
        //声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3为有用户申请退单了。默认为 2 来单播放模式
        request.setVoice(2);
        //打印模式：
        //值为 0 或不指定则会检查打印机是否在线，如果不在线 则不生成打印订单，直接返回设备不在线状态码；如果在线则生成打印订单，并返回打印订单号。
        //值为 1不检查打印机是否在线，直接生成打印订单，并返回打印订单号。如果打印机不在线，订单将缓存在打印队列中，打印机正常在线时会自动打印。
        request.setMode(0);
        // 打印接口回调地址对应标识(取值范围 [ 1 - 5 ] 的整数)，对于web管理后台 “功能设置” 菜单设置界面的打印接口回调标识。
        // request.setBackurlFlag(1);

        ObjectRestResponse<String> resp = printService.print(request);
        return resp.getCode() == 0;
    }

    private     String  getPrenter(Map<String, Object> orderMaster, List<Map<String, Object>> orderDetails){
        Timestamp createDate = (Timestamp) orderMaster.get("createDate");
        System.out.println("createDate:"+createDate);
        String format = DateUtil.format(createDate, "yyyy-MM-dd HH:mm:ss");
        PrinterQuery printerQuery=new PrinterQuery();
        printerQuery.rtl();
        printerQuery.cb("圆规公司");
        printerQuery.br();
        printerQuery.addRow("نۇمۇرى:"+orderMaster.get("sn"));
        printerQuery.addRow("زاكاس ۋاقتى:"+format);
        printerQuery.line58();
        printerQuery.addGoodsHeader("نامى","سانى","باھاسى");
        printerQuery.line58();
        Iterator<Map<String, Object>> iterator = orderDetails.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> next = iterator.next();
            int count =(int)next.getOrDefault("quantity", 0);
            BigDecimal price =(BigDecimal)next.getOrDefault("price", 0);
            printerQuery.addGoods((String) next.get("goodsName"), count,price);

        }
        //  printerQuery.addGoods("Test",2,BigDecimal.valueOf(3.5));
        //  printerQuery.addGoods("Test1",3,BigDecimal.valueOf(4.5));
        printerQuery.line58();
        printerQuery.addRow("ئەسلى سومما:"+orderMaster.get("totalAmount")+"￥");
        printerQuery.addRow("تۆلەنگەن سومما:"+orderMaster.get("paymentAmount")+"￥");
        printerQuery.addRow(" چۈشۈرگۈچى:"+orderMaster.get("userName"));
        printerQuery.addRow(" تېلفۇن:"+(orderMaster.get("phone")!=null?orderMaster.get("phone"):"---"));
        printerQuery.line58();
        printerQuery.addRow("<C>"+(orderMaster.get("address")!=null?orderMaster.get("address"):"---")+"<C>");


        return printerQuery.build();
    }

}




